<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 *  Controls the database operations over the costumes of a given user.
 *  
 * @package com_musashi
 * @author Daniel Torres
 */
 
// Make sure we have access to this page
defined('_JEXEC') or die ('Restricted access');

jimport('joomla.application.component.model');

/**
 *  
 *  Model for all Costumes-related operations
 *  @author Daniel Torres
 */
 class MusashiModelCostumes extends JModel
 {
    var $_musashiMemberID = null;     // The Musashi ID of the current member (as specified on the Member table)
    
   /**
     *  Obtains the member id of the current user. This function could be placed
     *  somewhere else (like the user module) and just passed to all other models,
     *  but for the sake of simplicity (and perhaps bad design) I'm just repeating it.
     *  
     *  WARNING: It is assumed that we have a member entry!
     */
    function getMemberID()
    {
        if( $this->_musashiMemberID == null )
        {
            // Get the current user
            $user =& JFactory::getUser();
        
            // See if we have him/her
            $query = "SELECT id FROM #__Musashi_Member WHERE userId =".$user->id;
            $this->_db->setQuery($query);
            $result = $this->_db->loadObject();
            
            if( $result != null ){
                $this->_musashiMemberID = $result->id;
            }

        }
        
        return $this->_musashiMemberID;
    }
    
    /**
     *   Returns an array with all the registered clothing types, in
     *   the form of [id, name] duples
     *   @return An array of [id, name] duples
     */
    function getClothingTypes()
    {
      $query = "SELECT id, name FROM #__Musashi_ClothingType";
      $this->_db->setQuery( $query );
      $results = $this->_db->loadRowList();
      
      return $results;      
    }
    
    /**
     *   Returns an array with costume entries
     *   @return An array of [id, name, description] duples
     */
    function getCostumes()
    {
      $query = "SELECT id, name, description FROM #__Musashi_Costume";
      $this->_db->setQuery( $query );
      $results = $this->_db->loadRowList();
      
      return $results;      
      
    }
    
    /**
     *   Returns clothing components of a given type
     *   @param a_type The type of clothing we are interested in
     *   @param a_bExcludeUserInventory If true, only return clothes NOT possessed by the user
     *   @return An array of [id, name, color, size] components
     */
   function getClothingByType( $a_type, $a_bExcludeUserInventory )
   {
        $query = "SELECT id,name,colour,size ".
                 "FROM #__Musashi_Clothing ".
                 "WHERE clothingType = ".$a_type;
                 
        if ( $a_bExcludeUserInventory )
        {
            $member = $this->getMemberID();
            $query .= " AND id NOT IN (".
                      "     SELECT idClothing ".
                      "     FROM #__Musashi_Member_Clothing ".
                      "     WHERE idMember = ".$member.")";
        }

        $this->_db->setQuery( $query );
        $result = $this->_db->loadRowList();
        
        return $result;
   }
   
   /**
    *  Returns the clothing pieces of a given type, owned by the current user
    *  @param a_type
    *  @return An array of [id, name, color] components
    */
   function getClothingByUser( $a_type )
   {
      $member = $this->getMemberID();
      
      if( $member != null )
      {
         $query = "SELECT c.id, c.name, c.colour FROM ".
                  "#__Musashi_Member_Clothing as m INNER JOIN ".
                  "#__Musashi_Clothing as c ".
                  "ON m.idClothing = c.id ".
                  "WHERE c.clothingType = ".$a_type." AND m.idMember = ".$member;
                  
         $this->_db->setQuery( $query );
         $result = $this->_db->loadRowList();
         
         return $result;
                  
      }
      else
      {
         return null;
      }
   }
   
   /**
    * Takes the provided array of clothing IDs, and adds them to the
    * member-clothing table.
    * @param a_clothingIDArray   An array of clothing IDs
    * @result The result of the addition query
    */
   function addClothingArray( $a_clothingIDArray )
   {
      // See if we can get enough information
      $member = $this->getMemberID();
      if( $member && is_array($a_clothingIDArray) )
      {
         // An empty array is a valid option too
         $records = count($a_clothingIDArray);
         if( $records > 0 )
         {
            $sql = "REPLACE INTO #__Musashi_Member_Clothing (idMember,idClothing) VALUES ";
            for( $i = 0; $i < $records; $i++ )
            {
               $sql .= sprintf('(%d,%d)', $member, $a_clothingIDArray[$i]);
               
               if( $i < $records - 1 ){
                  $sql .=',';
               } else {
                  $sql .= ';';
               }               
            }
            
            // Execute
            $this->_db->setQuery( $sql );
            return $this->_db->query();
            
         }
         
         return true;         
      }
      else
      {
         return false;
      }
   }
   
   /**
    * Adds the components of a given costume into the user's inventory
    * @param a_costumeID   The ID of the desired costume
    */
   function addCostume( $a_costumeID )
   {
      // Create an array of clothing IDs, and delegate to addClothingArray
      $sql = "SELECT idClothing FROM #__Musashi_Clothing_Costume WHERE idCostume = ".$a_costumeID;
      $this->_db->setQuery( $sql );
      
      $costumeIDArray = $this->_db->loadResultArray();
      if( $costumeIDArray != null )
      {
         return $this->addClothingArray( $costumeIDArray );
      }
      
      // If we produced no results, that 'might' be valid. It just means the
      // selected costume has no pieces yet
      return true;
   }
   
   /**
    * Removes clothing from the user's list, given the provided array of clothing IDs
    * @param a_clothingIDArray   An array of clothing IDs
    * @result The result of the addition query
    */
   function removeClothingArray( $a_clothingIDArray )
   {
      // See if we can get enough information
      $member = $this->getMemberID();
      if( $member && is_array($a_clothingIDArray) )
      {
         // An empty array is a valid option too
         $records = count($a_clothingIDArray);
         if( $records > 0 )
         {
            $sql = "DELETE FROM #__Musashi_Member_Clothing  ".
                   "WHERE idMember = ".$member." ".
                   "AND idClothing IN (";
                   
            for( $i = 0; $i < $records; $i++ )
            {
               $sql .= $a_clothingIDArray[$i];
               
               if( $i < $records - 1 ){
                  $sql .=',';
               }               
            }
            
            $sql.= ');';
            
            // Execute
            $this->_db->setQuery( $sql );
            return $this->_db->query();
            
         }
         
         return true;         
      }
      else
      {
         return false;
      }
      
   }
    
      

    
 }
?>
